package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.ProductCategory;
import com.sskj.api.exception.LogicException;
import com.sskj.api.mapper.ProductCategoryMapper;
import com.sskj.api.service.IProductCategoryService;
import com.sskj.api.vo.req.ProductCategoryPageListReq;
import com.sskj.common.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class ProductCategoryService extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements IProductCategoryService {

    @Override
    public void add(ProductCategory productCategory) {
        LambdaQueryWrapper<ProductCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProductCategory::getName, productCategory.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("分类名称已存在");
        }

        productCategory.setCreateTime(LocalDateTime.now());
        save(productCategory);
    }

    @Override
    public void deleteById(Long id) {
        removeById(id);
    }

    @Override
    public void update(ProductCategory productCategory) {
        LambdaQueryWrapper<ProductCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProductCategory::getName, productCategory.getName())
                .ne(ProductCategory::getId, productCategory.getId());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("分类名称已存在");
        }

        productCategory.setUpdateTime(LocalDateTime.now());
        updateById(productCategory);
    }

    @Override
    public IPage<ProductCategory> pageList(ProductCategoryPageListReq req) {
        LambdaQueryWrapper<ProductCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(ProductCategory::getSortOrder)
                .orderByDesc(ProductCategory::getId);
        if (StrUtil.isNotBlank(req.getName())) {
            lambdaQueryWrapper.like(ProductCategory::getName, req.getName());
        }
        if (req.getStatus() != null && req.getStatus() > 0) {
            lambdaQueryWrapper.eq(ProductCategory::getStatus, req.getStatus());
        }

        IPage<ProductCategory> pageConfig = new Page<>(req.getPageNum(), req.getPageSize());
        return page(pageConfig, lambdaQueryWrapper);
    }
}
